package com.gl.order.security.service;

import com.gl.order.entity.TUser;
import com.gl.order.mapper.TRoleMapper;
import com.gl.order.security.model.SecurityUser;
import com.gl.order.service.PermissionService;
import com.gl.order.service.RoleService;
import com.gl.order.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    UserService userService;

    @Autowired
    PermissionService permissionService;

    @Autowired
    TRoleMapper roleMapper;


    //根据账号查询用户信息
    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        TUser user = userService.findUserByAccount(account);
        if(user == null){
            //如果用户查不到，返回null，由provider来抛出异常
            log.info("user not found :"+account);
            throw new UsernameNotFoundException("用户不存在");
        }
        // 获取用户角色
        List<String> roles = roleMapper.findByUser(user.getId());
        SecurityUser securityUser = new SecurityUser(user);
        securityUser.setPermissionsList(roles);
        return securityUser;
    }
}
